import { defineStore } from 'pinia'
import Cookies from 'js-cookie'
import type { User, LoginForm, RegisterForm } from '@/types'
import { api } from '@/api/request'
import { mockLogin } from '@/api/mock'

export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref<User | null>(null)
  const token = ref<string | null>(localStorage.getItem('token'))
  const isLoggedIn = computed(() => !!token.value && !!user.value)
  
  // 登录
  const login = async (form: LoginForm) => {
    try {
      // 使用模拟登录进行测试
      const response = await mockLogin(form.username, form.password)

      if (response.success && response.data) {
        user.value = response.data.user
        token.value = response.data.token

        // 保存到 localStorage 和 cookies
        localStorage.setItem('token', response.data.token)
        localStorage.setItem('user', JSON.stringify(response.data.user))
        Cookies.set('token', response.data.token, { expires: 7 }) // 7天过期
        Cookies.set('user', JSON.stringify(response.data.user), { expires: 7 })

        window.$message?.success('登录成功')
        return true
      }
      return false
    } catch (error) {
      console.error('Login error:', error)
      window.$message?.error(error instanceof Error ? error.message : '登录失败')
      return false
    }
  }

  // 匿名登录
  const loginAsGuest = async () => {
    try {
      // 创建匿名用户
      const guestUser: User = {
        id: 0,
        username: 'guest',
        email: 'guest@local',
        nickname: '游客',
        avatar_url: '',
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
        is_active: true,
        is_anonymous: true
      }

      const guestToken = `guest_token_${Date.now()}`

      user.value = guestUser
      token.value = guestToken

      // 保存到 localStorage 和 cookies
      localStorage.setItem('token', guestToken)
      localStorage.setItem('user', JSON.stringify(guestUser))
      Cookies.set('token', guestToken, { expires: 7 })
      Cookies.set('user', JSON.stringify(guestUser), { expires: 7 })

      window.$message?.success('欢迎体验！')
      return true
    } catch (error) {
      console.error('Guest login error:', error)
      window.$message?.error('匿名登录失败')
      return false
    }
  }
  
  // 注册
  const register = async (form: RegisterForm) => {
    try {
      const response = await api.post<{ user: User; token: string }>('/auth/register', form)

      if (response.success && response.data) {
        user.value = response.data.user
        token.value = response.data.token

        // 保存到 localStorage 和 cookies
        localStorage.setItem('token', response.data.token)
        localStorage.setItem('user', JSON.stringify(response.data.user))
        Cookies.set('token', response.data.token, { expires: 7 })
        Cookies.set('user', JSON.stringify(response.data.user), { expires: 7 })

        window.$message?.success('注册成功')
        return true
      }
      return false
    } catch (error) {
      console.error('Register error:', error)
      return false
    }
  }

  // 登出
  const logout = async () => {
    try {
      // 可以调用 API 通知服务器（如果需要）
      // await api.post('/auth/logout')
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      // 清除本地存储
      user.value = null
      token.value = null
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      Cookies.remove('token')
      Cookies.remove('user')

      window.$message?.success('已退出登录')
    }
  }
  
  // 获取用户信息
  const fetchUserInfo = async () => {
    if (!token.value) return false
    
    try {
      const response = await api.get<User>('/auth/me')
      
      if (response.success && response.data) {
        user.value = response.data
        return true
      }
      return false
    } catch (error) {
      console.error('Fetch user info error:', error)
      // 如果获取用户信息失败，清除token
      logout()
      return false
    }
  }
  
  // 更新用户信息
  const updateUserInfo = async (data: Partial<User>) => {
    try {
      const response = await api.put<User>('/auth/profile', data)
      
      if (response.success && response.data) {
        user.value = response.data
        window.$message?.success('信息更新成功')
        return true
      }
      return false
    } catch (error) {
      console.error('Update user info error:', error)
      return false
    }
  }
  
  // 修改密码
  const changePassword = async (oldPassword: string, newPassword: string) => {
    try {
      const response = await api.put('/auth/password', {
        old_password: oldPassword,
        new_password: newPassword
      })
      
      if (response.success) {
        window.$message?.success('密码修改成功')
        return true
      }
      return false
    } catch (error) {
      console.error('Change password error:', error)
      return false
    }
  }
  
  // 初始化（检查登录状态）
  const init = async () => {
    // 优先从 cookies 恢复状态，然后是 localStorage
    const cookieToken = Cookies.get('token')
    const cookieUser = Cookies.get('user')
    const localToken = localStorage.getItem('token')
    const localUser = localStorage.getItem('user')

    const savedToken = cookieToken || localToken
    const savedUser = cookieUser || localUser

    if (savedToken && savedUser) {
      try {
        token.value = savedToken
        user.value = JSON.parse(savedUser)

        // 如果从 localStorage 恢复，同时保存到 cookies
        if (!cookieToken && localToken) {
          Cookies.set('token', savedToken, { expires: 7 })
          Cookies.set('user', savedUser, { expires: 7 })
        }

        console.log('用户状态已恢复:', user.value?.username)
      } catch (error) {
        console.error('恢复用户状态失败:', error)
        // 清除损坏的数据
        logout()
      }
    }
  }
  
  return {
    // state
    user: readonly(user),
    token: readonly(token),
    isLoggedIn,

    // actions
    login,
    loginAsGuest,
    register,
    logout,
    fetchUserInfo,
    updateUserInfo,
    changePassword,
    init
  }
})
